String to Integer

Implement atoi to convert a string to an integer.

Hint:

Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.

Notes:

It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.

Solution:

  1. public class Solution {
  2. public int myAtoi(String str) {
  3. if (str == null) {
  4. return 0;
  5. }
  6. // trim the leading and trailing spaces
  7. str = str.trim();
  8. if (str.length() == 0) {
  9. return 0;
  10. }
  11. char[] chars = str.toCharArray();
  12. boolean positive = true;
  13. int i = 0;
  14. if (chars[0] == '-') {
  15. positive = false;
  16. i = 1;
  17. }
  18. if (chars[0] == '+') {
  19. i = 1;
  20. }
  21. int num = 0;
  22. while (i < chars.length) {
  23. char ch = chars[i++];
  24. if (ch < '0' || ch > '9') {
  25. return num;
  26. }
  27. int d = (int)(ch - '0');
  28. if (positive) {
  29. if (num > (Integer.MAX_VALUE - d) / 10) {
  30. return Integer.MAX_VALUE;
  31. }
  32. num = num * 10 + d;
  33. } else {
  34. if (num < (Integer.MIN_VALUE + d) / 10) {
  35. return Integer.MIN_VALUE;
  36. }
  37. num = num * 10 - d;
  38. }
  39. }
  40. return num;
  41. }
  42. }